<?php
/**
 * 收款单控制器
 * @author Max.Yu <max@jipu.com>
 */

namespace Shop\Controller;

use Think\Page;

class BillController extends CommonController{

  /**
   * 收款单列表
   * @author Max.Yu <max@jipu.com>
   */
  public function index($keywords = null,$flow = null){
    //实例化收款单模型
    $Payment = M('StoreCash');

    //查询条件初始化
    $where = array('store_id'=>$this->store_id);

      //查询条件：支付编号或订单编号
      if($keywords){
          $payment_order=M('Order')->where(array('order_sn'=>array('LIKE','%'.$keywords.'%')))->field('payment_id')->select();
          $payment_ids=array_column($payment_order,'payment_id');
          if(!$payment_ids)$payment_ids=array(0);
          $where['_string'] = '(remark like "%'.$keywords.'%") OR (trade_sn in ('.implode(',',$payment_ids).'))';
      }
      if($flow){
          $where['flow|type'] = $flow;
      }
      if($flow == 'cousume'){
          $where['flow|type'] = array('in',array('consume',' consume'));
      }
      //交易类型
      $type = array(
          '用户消费'=> 'consume',
          '用户退款'=>'refund',
          '店铺促销活动费用'=>'store_cost',
          '三级分销'=>'sdp_dis',
          '分销店铺'=>'sdp_order',
          '商家提现'=>'apply'
      );
      //按条件查询结果并分页
      $list = $this->lists($Payment, $where, 'id desc');

    //记录当前列表页的Cookie
    Cookie('__forward__', $_SERVER['REQUEST_URI']);
    $remark=$Payment->field('distinct(remark)')->select();
    $this->assign('remark', $remark);
    //模板输出变量赋值
    foreach ($list as $key => $value) {
      $list[$key]['order_sn'] = M('Order')->where(array('id'=>$value['order_id']))->getField('order_sn');
    }
    $this->assign('type',$type);
    $this->assign('list', $list);
    $this->meta_title = '收款单列表';
    $this->display();
  }

  /**
   * 申请提现
   */
  public function add(){
      $where = array(
          'store_id' => $this->store_id,
          'status'   => array('not in' , '2,4' )
      );
      $where['status'] = array('in' , '5' );
      //已提现部分
      $this->Withdrawed= sprintf('%.2f' ,M('StoreWithdraw')->where($where)->sum('amount'));
      $where['status'] = array('in' , '1,3' );
      //提现申请中
      $this->withouting= sprintf('%.2f' ,M('StoreWithdraw')->where($where)->sum('amount'));
      $map = array(
          'store_id' => $this->store_id,
          'o_status' => array('in' , '-3,200,201,202'),//付款后
      );
      //总金额
      $this->total_amount = M('Order')->where($map)->getField('sum(total_price) + sum(delivery_fee) ');

      //待支付
      $this->unpay_amount = M('Order')->where(array('store_id'=>$this->store_id,'o_status'=>0))->getField('sum(total_price) + sum(delivery_fee)');
      //已支付
      $this->ispay_amount = M('Order')->where(array('store_id'=>$this->store_id,'payment_time'=>array('gt',0)))->getField('sum(total_price) + sum(delivery_fee) ');
      //退款
      $this->refund_amount = M('Order')->where(array('store_id'=>$this->store_id,'o_status'=>array('IN', '300,301,302,303')))->getField('sum(total_price) + sum(delivery_fee) ');
      //交易成功
      $this->success_amount = M('Order')->where(array('store_id'=>$this->store_id,'o_status'=>202))->getField('sum(total_price) + sum(delivery_fee) ');

      $model = M('StoreCash');
      //商户申请提现，将退款的记录排除掉（平台延误，不能实现同步），直接从订单中查询，实现同步
      //收入部分
      $in_total=$model->where(array('flow'=>'in','status'=>array('GT',0),'type'=>array('neq','refund'),'store_id'=>$this->store_id))->sum('amount');

      // 输出部分
      $out_total=$model->where(array('flow'=>'out','status'=>array('GT',0),'type'=>array('neq','refund'),'store_id'=>$this->store_id))->sum('amount');
      $max_refund_cash_time = time() - (C('MAX_REFUND_CASH_DAY')*60*60*24);
      // 订单未完成部分或者完成了但未过保护时间部分 修改部分
      $no_complete_order=M('StoreOrder')->field('order_sn')->where('(o_status in (200,201,300,301,302,304,404,405) OR complete_time>'.$max_refund_cash_time.') AND store_ids='.$this->store_id)->select();
      $order_sns = array_column($no_complete_order,'order_sn');
      if (count($order_sns)) {
        foreach ($order_sns as $key => $value) {
          $order_ids[] = M('Order')->where(array('order_sn='.$value))->getField('id');
        }
      }
      //$order_ids=array_column($no_complete_order,'id');
      if(count($order_ids) > 0){
          $no_in_total=$model->where(array('order_id'=>array('in',$order_ids),'flow'=>'in','status'=>array('GT',0)))->sum('amount');
          $no_out_total=$model->where(array('order_id'=>array('in',$order_ids),'flow'=>'out','status'=>array('GT',0)))->sum('amount');
      }else{
          $no_in_total=0;
          $no_out_total=0;
      }
      $applying = $model->where('store_id ='.$this->store_id.' and status = 2 and type ="apply"')->sum('amount');
      $this->total_price=$in_total-$out_total +  $applying;
      // 申请提现部分；
      $now_price = sprintf('%.2f',$this->total_price-$no_in_total+$no_out_total - $applying);
      $this->now_price =  $now_price > 0 ? $now_price : '0.00' ;
      if(IS_POST){
          $amount=I('post.amount');
          if( ($amount <= 0) || (sprintf('%.2f',$amount)) > $now_price)$this->error( '提现金额输入错误！');

          $StoreCash = M('StoreCash');
          //现金流水表信息
          $now_time=time();
          $sc_data=array(
              'uid'=>$this->sellerInfo['member_id'],
              'store_id'=>$this->store_id,
              'order_id'=>'',
              'trade_sn'=>$now_time,
              'type'=>'apply',//商家提现
              'trade_type'=>'web',
              'flow'=>'out',
              'amount'=>$amount,
              'ctime'=>$now_time,
              'remark'=>'商户提现'.I('post.remark'),
              'status'=>2
          );
          $store_data = array(
              'uid'=>$this->sellerInfo['member_id'],
              'store_id'=>$this->store_id,
              'amount'=>$amount,
              'ctime'=>$now_time,
              'memo'=>trim(I('post.remark')),
              'status'=>1
            );

          //开启事务
          $StoreCash->startTrans();
          $res = $StoreCash->add($sc_data);

          $res1 = M('StoreWithdraw')->add($store_data);

          if(false !== $res && $res1 !== false){
            //提交事务
            $StoreCash->commit();
            $this->success('操作成功！', Cookie('__forward__'));
          }else{
            //事务回滚
            $StoreCash->rollback();
            $error = $model->getError();
            $this->error(empty($error) ? '未知错误！' : $error);
          }
      }else{
          $this->info=M('StoreApply')->where(array('member_id'=>$this->sellerInfo['member_id']))->find();
          $this->display('edit');
      }
  }

  /**
   * 商户提现列表
   * @author buddha <[email address]>
   * @return [type] [description]
   */
  public function cashList($keywords = null,$status = null){
    $StoreWithdraw = M('StoreWithdraw');
    $where['store_id'] = $this->store_id;
    //查询条件：
    if($keywords){
        $where['_string'] = '(memo like "%'.$keywords.'%") OR (remark like "%'.$keywords.'%")';
    }
    if($status){
        $where['status'] = $status;
    } 
    //按条件查询结果并分页
    $list = $this->lists($StoreWithdraw, $where, 'id desc');
    //数据重组
    foreach ($list as $key => $value) {
      $member_id = M('Seller')->where(array('store_id'=>$value['store_id']))->getField('member_id');
      $store_row=M('StoreApply')->where(array('member_id'=>$member_id))->field('settlement_bank_account_name,settlement_bank_account_number')->find();
      $list[$key]['bank_name'] = $store_row['settlement_bank_account_name'];
      $list[$key]['bank_account'] = $store_row['settlement_bank_account_number'];
    }
    //记录当前列表页的Cookie
    Cookie('__forward__', $_SERVER['REQUEST_URI']);
    $this->assign('list', $list);
    $this->status = get_store_withdraw_text();
    $this->meta_title = '提现列表';
    $this->display();

  }

  public function update($model = CONTROLLER_NAME){
      if(false !== M('StoreCash')->save(I('get.'))){
          $this->success('操作成功！', Cookie('__forward__'));
      }else{
          $error = $model->getError();
          $this->error(empty($error) ? '未知错误！' : $error);
      }
  }

    /**
   * 查看收款单
   * @author Max.Yu <max@jipu.com>
   */
  public function view($id = 0){
    /* 获取数据 */
    $info = array();
    $info = M('Payment')->find($id);
    $payment_type = $this->payment_type;
    $info['payment_type_text'] = !is_array(get_payment_type_text($info['payment_type'])) ? get_payment_type_text($info['payment_type']) : '';
    if(false === $info){
      $this->error('数据获取错误');
    }

    //获取订单信息
    $this->order_lists = M('Order')->field('id, order_sn, create_time')->where(array('payment_id' => $id))->select();
    //获取订单明细
    $order_ids = array_column($this->order_lists, 'id');
    $orderItemInfo = get_order_item($order_ids);
    //获取订单统计信息
    $orderCount = count_order_item($order_ids);
    //模板输出变量赋值
    $this->assign('info', $info);
    $this->assign('orderItemInfo', $orderItemInfo);
    $this->assign('orderCount', $orderCount);
    $this->meta_title = '收款单详情';
    $this->display();
  }
  
  /**
  * 去掉重复
  * @version 2015073015
  * @author Justin
  */
  function removeDuplicate(){
    R('Update/removeDuplicate', array('jipushop_payment', 'payment_sn')) && $this->success('去重成功！', Cookie('__forward__'));
  }
  
  /**
   * 收款单预览
   * @version 2015090816
   * @author Max.Yu <max@jipu.com>
   */
  public function preview($payment_id = 0){
    $data = M('Payment')->getById($payment_id);
    $data['payment_item_price'] = sprintf('%.2f', get_count_payment_price($data['id'])); //商品总价格
    $data['payment_delivery'] = sprintf('%.2f', get_count_payment_price($data['id'], 'delivery_fee')); //运费总价格
    $data['system_discount'] = sprintf('%.2f', $data['payment_item_price'] + $data['payment_delivery'] - $data['payment_amount'] - $data['finance_amount'] - $data['score_amount'] - $data['manjian'] - $data['coupon_amount'] - $data['card_amount']); //平台优惠金额
    $data['delivery_price'] = get_count_payment_price($data['id'], 'delivery_fee');
    $this->assign('data', $data);
    $this->display();
  }
  
}
